const { readFileSync, writeFileSync } = require('fs')
const envConfig = require('./env_config.json')

// 更改 .env变量
module.exports = (mode) => {
    const data = readFileSync(envConfig.env_path, 'utf8')
    const modeState = {
        dev: {
            api: envConfig.dev_api,
            shoudao_studio_api: envConfig.dev_shoudao_studio_api,
            ai_chat_api: envConfig.dev_ai_chat_api,
            mode: 'development',
        },
        pro: {
            api: envConfig.pro_api,
            shoudao_studio_api: envConfig.pro_shoudao_studio_api,
            ai_chat_api: envConfig.pro_ai_chat_api,
            mode: 'production',
        },
    }
    const newEnv = () => {
        let _oldEnv = JSON.parse(JSON.stringify(data))
        _oldEnv = _oldEnv.replace(/^NODE_ENV=.*/gm, `NODE_ENV=\'${modeState[mode].mode}\'`)
        _oldEnv = _oldEnv.replace(/^VITE_APP_BASE_API=.*/gm, `VITE_APP_BASE_API=\'${modeState[mode].api}\'`)
        _oldEnv = _oldEnv.replace(/^VITE_SHOUDAO_STUDIO_URL=.*/gm, `VITE_SHOUDAO_STUDIO_URL=\'${modeState[mode].shoudao_studio_api}\'`)
        _oldEnv = _oldEnv.replace(/^VITE_AI_CHAT_URL=.*/gm, `VITE_AI_CHAT_URL=\'${modeState[mode].ai_chat_api}\'`)
        return _oldEnv
    }
    writeFileSync(envConfig.env_path, newEnv())
    console.log('环境变量编译完成！')
}
